﻿using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml;
using MouseExtender.Logic.Common;
using MouseExtender.Logic.Entities;

namespace MouseExtender.Logic.Managers
{
	public class ExternalResourcesManager
	{
		private static ThumbsData _thumbsData = null;
		private static string _thumbsFilePath = null;

		public static ThumbsData Thumbs
		{
			get
			{
				return _thumbsData;
			}
		}

		public static string ThumbsFilePath
		{
			get
			{
				if (_thumbsFilePath == null)
				{
					Assembly meAssembly = Assembly.GetExecutingAssembly();
					string currentDirectory = Path.GetDirectoryName(meAssembly.Location);
					_thumbsFilePath = Path.Combine(currentDirectory, Constants.ThumbsFileName);
				}

				return _thumbsFilePath;
			}
		}

		static ExternalResourcesManager()
		{
			ReloadThumbs();
		}

		public static void ReloadThumbs()
		{
			try
			{
				if (!File.Exists(ThumbsFilePath))
				{
					_thumbsData = new ThumbsData();
				}
				else
				{
					using (FileStream stream = new FileStream(ThumbsFilePath, FileMode.Open, FileAccess.Read))
					{

						XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas()
							 {
								 MaxBytesPerRead = Int32.MaxValue,
								 MaxArrayLength = Int32.MaxValue
							 };

						using (XmlDictionaryReader binaryDictionaryReader = XmlDictionaryReader.CreateBinaryReader(stream, quotas))
						{
							DataContractSerializer serializer = new DataContractSerializer(typeof(ThumbsData));
							_thumbsData = (ThumbsData)serializer.ReadObject(binaryDictionaryReader);
						}
					}
				}
			}
			catch (Exception ex)
			{
				Logger.HandleNonCriticalError(ex);
			}
		}

		public static void SaveThumbs()
		{
			NormalizeData();

			try
			{
				using (FileStream stream = new FileStream(ThumbsFilePath, FileMode.Create, FileAccess.ReadWrite))
				{
					using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream))
					{
						DataContractSerializer serializer = new DataContractSerializer(typeof(ThumbsData));
						serializer.WriteObject(binaryDictionaryWriter, _thumbsData);
					}
				}
			}
			catch (Exception ex)
			{
				Logger.HandleNonCriticalError(ex);
			}
		}

		/// <summary>
		/// Remove obsoleted thumbs
		/// </summary>
		private static void NormalizeData()
		{
			Thumbs.CleanupThumbs(SettingsManager.CurrentSettings.LauncherItems);
		}


	}
}
